package org.serverct.finalfight.game.gui;

import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
import org.serverct.finalfight.FinalFight;
import org.serverct.finalfight.util.CustomSettings;

import java.io.File;
import java.io.IOException;

public class PersistentInventory {
    public static void saveInventory(Player player) {
        File file = CustomSettings.getFile("/inventory/", player.getUniqueId().toString() + ".yml");
        if (file.exists()) {
            if (!file.delete()) {
                FinalFight.plugin.getLogger().warning("§c保存玩家背包数据时出现错误！");
            }
        }
        YamlConfiguration yaml = YamlConfiguration.loadConfiguration(file);
        PlayerInventory inv = player.getInventory();
        for (int i = 0; i < inv.getSize(); i++) {
            if (inv.getItem(i) != null) {
                yaml.set(String.valueOf(i), inv.getItem(i));
            }
        }
        try {
            yaml.save(file);
        } catch (IOException e) {
            FinalFight.plugin.getLogger().warning("§c保存玩家§e " + player.getName() + "§c 的背包数据时出现错误！");
        }
    }

    public static void loadInventory(Player player) {
        File file = CustomSettings.getFile("/inventory/", player.getUniqueId().toString() + ".yml");
        if (!file.exists()) {
            return;
        }
        YamlConfiguration yaml = YamlConfiguration.loadConfiguration(file);
        clearInventory(player);
        PlayerInventory inv = player.getInventory();
        for (String path : yaml.getKeys(false)) {
            inv.setItem(Integer.parseInt(path), yaml.getItemStack(path));
        }
        if (!file.delete()) {
            FinalFight.plugin.getLogger().warning("§c保存玩家背包数据时出现错误！");
        }
    }

    public static void clearInventory(Player player) {
        PlayerInventory inv = player.getInventory();
        inv.clear();
    }
}
